import axios from 'axios';
import { Toast } from 'vant';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { isLogined } from './util';

// 创建一个axios实例，这里面的API是固定的，比如baseURL
const instance = axios.create({
  timeout: 5000,
  baseURL: 'http://localhost:1337',
});

// https://github.com/axios/axios
// 全局拦截器
// Add a request interceptor
//  全局请求拦截，发起网络请求之前执行
instance.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    NProgress.start(); // 启动进度条
    // eslint-disable-next-line no-param-reassign
    config.headers.token = isLogined();
    return config;
  },
  // eslint-disable-next-line comma-dangle
  (error) => Promise.reject(error)
);

// Add a response interceptor
// 全局响应拦截，网络请求完成之后执行
instance.interceptors.response.use(
  (response) => {
    NProgress.done(); // 关闭进度条
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  },
  (error) => {
    // console.dir(error);
    if (error.response.status === 401) {
      Toast.fail('请重新登录');
      setTimeout(() => {
        window.location.href = '/#/login';
      }, 3000);
    }
    NProgress.done(); // 关闭
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
    // eslint-disable-next-line comma-dangle
  }
);
// eslint-disable-next-line import/prefer-default-export
export const get = (url, params) => instance.get(url, { params });
export const post = (url, data) => instance.post(url, data);
export const del = (url) => instance.delete(url);
export const put = (url, data) => instance.put(url, data);
